package com.example.mediamoudle.systime

import android.content.Intent
import android.graphics.SurfaceTexture
import android.opengl.GLES20
import android.util.Log
import android.view.Surface
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.base.BaseActivity
import com.android.baselibrary.video.VideoExt
import com.example.mediamoudle.R
import com.example.mediamoudle.databinding.ActivitySysCodecVideoBinding
import com.example.mediamoudle.pickvideo.PickVideoActivity
import com.example.mediamoudle.pickvideo.VideoFile
import com.example.mediamoudle.router.MediaRouterPath
import com.example.mediamoudle.systime.decoder.AudioDecoder
import com.example.mediamoudle.systime.decoder.VideoDecoder
import kotlinx.coroutines.runBlocking
import java.util.concurrent.Executors

/**
 * 时间同步
 */
@Route(path = MediaRouterPath.MEDIA_DECODE_SYS_VIDEO)
class SysTimeVideoActivity :BaseActivity<ActivitySysCodecVideoBinding>(), View.OnClickListener {
    override fun getLayoutId(): Int = R.layout.activity_sys_codec_video

    override fun initView() {
        mBinding.click = this

    }

    override fun initListener() {


    }

    override fun onClick(v: View?) {
        when (v?.id){
            R.id.button ->{

            }
            R.id.button_chose ->{
                startActivityForResult(Intent(this, PickVideoActivity::class.java), 1000)
            }

        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 2000) {
            val path = data?.getParcelableArrayListExtra<VideoFile>("videoPath") as ArrayList<VideoFile>
            Log.i("TAG", "onActivityResult: path:$path")
            if (path != null) {
               initPlayer(path[0].path)
            }


        }
    }
    var audioDecoder:AudioDecoder?=null
    fun initPlayer(videoPath:String){
        val threadPool = Executors.newFixedThreadPool(10)
        val  videoDrawer = VideoDrawer()
        val videoInfo =  VideoExt.getVideoInfo(videoPath)

        videoDrawer.getSurfaceTexture {
            //创建纹理
            val textures = IntArray(1)
            //生成纹理
            GLES20.glGenTextures(1, textures, 0)
            val surfaceTexture = SurfaceTexture(textures[0])
            val surface = Surface(surfaceTexture)

            val  videoDecoder = VideoDecoder(videoPath, Surface(it))
            threadPool.execute(videoDecoder)

             audioDecoder = AudioDecoder(videoPath)
            threadPool.execute(audioDecoder)

            videoDecoder.goOn()
            audioDecoder?.goOn()





        }
        videoDrawer.setVideoSize(videoInfo.width,videoInfo.height)
        mBinding.surface.setEGLContextClientVersion(2)
        mBinding.surface.setRenderer(VideoRender(videoDrawer){

        })



    }
}